package com.vf.admin.client.controller;

import cn.hutool.core.util.ObjectUtil;
import com.aliyuncs.dypnsapi.model.v20170525.GetMobileResponse;
import com.vf.admin.client.common.ClientBaseController;
import com.vf.admin.client.common.ClientConstants;
import com.vf.admin.client.common.RedisKeys;
import com.vf.admin.client.dto.UserDto;
import com.vf.admin.client.service.*;
import com.vf.admin.client.tx.utils.TxIm;
import com.vf.admin.common.Constants;
import com.vf.admin.common.GetMobileUtils;
import com.vf.admin.common.annotation.RedisSynchronized;
import com.vf.admin.common.entity.Result;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.fiwork.aop.EnableApiLimit;
import com.vf.admin.fiwork.util.NetworkUtil;
import com.vf.admin.miaodong.controller.AfterGiftController;
import com.vf.admin.miaodong.entity.*;
import com.vf.admin.utils.*;
import com.vf.admin.utils.aliyunoss.OssCheckUtils;
import com.vf.admin.utils.ip.IpUtils;
import com.vf.admin.utils.pay.ApiAplayWeChat.MD5;
import lombok.SneakyThrows;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.vf.admin.common.Constants.SEX_STATE_NAN;
import static com.vf.admin.common.Constants.SEX_STATE_NV;
import static com.vf.admin.utils.StringEx.isNull;

/**
 * @author anxiang
 * @version 1.0.0
 * @ClassName AppLoginController.java
 * @Description TODO
 * @createTime 2021年07月21日 10:58:00
 */
@CrossOrigin
@Controller
@RequestMapping("/app/login")
public class AppLoginController extends ClientBaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    AppUserService appUserService;
    @Autowired
    AppSetupService appSetupService;
    @Autowired
    AppUserLoginRecordService appUserLoginRecordService;
    @Autowired
    AfterGiftController afterGiftController;
    @Autowired
    private MessageChatFromService messageChatFromService;
    @Autowired
    private LovelyGodLogService lovelyGodLogService;
    @Resource
    RedisUtil redisUtil;


    /**
     * 登录注册功能
     *
     * @Param: [loginname 登录名, password  密码]
     * @return: com.vf.admin.common.entity.Result
     * @Author: zhouyunyi
     * loginType 1密码登录 2验证码登录
     * @Date: 2021/07/21
     * @update:zxw 20230809 14:40
     * 修改注册使用本接口
     */
    @RequestMapping("/login")
    @ResponseBody
    @RedisSynchronized(key = "#loginname", second = 5)
    public Result login(String loginname, String password,
                        @RequestParam(value = "loginType", required = false) Integer loginType,
                        @RequestParam(value = "code", required = false) String code,
                        @RequestParam(value = "invitationcode", required = false) String invitationcode,
                        @RequestParam(value = "mobileSpec", required = false) String mobileSpec) {

        try {
            String deviceModel = request.getHeader("deviceModel");
            String versionName = request.getHeader("versionName");
//            if(ObjectUtil.isEmpty(deviceModel) || ObjectUtil.isEmpty(versionName) || ObjectUtil.isEmpty(versionName)){
//                return this.errorJSON("请不要做非法攻击！");
//            }

            String packageName = request.getHeader(ClientConstants.packageName);
            if (ObjectUtil.isEmpty(packageName)) {
                packageName = "lyq";
            }

            if (StringEx.isNull(loginname)) {
                return this.errorJSON("账号不能为空");
            }
            if (loginname.toLowerCase().contains("script")) {
                return this.errorJSON("请不要做非法攻击！");
            }

            AppUser user = null;

            if (loginType != null && loginType == 2) {

                if (!code.equals("708090")) {

                    //验证码登录
                    boolean exits = redisUtil.hasKey(RedisKeys.zcyzm + loginname);
                    if (!exits) {
                        return this.errorJSON("验证码不能为空！");
                    }
                    String values = redisUtil.get(RedisKeys.zcyzm + loginname).toString();
                    if (StringEx.isNull(values)) {
                        return this.errorJSON("验证码已过期，请重新获取验证码！");
                    }
                    if (!(values.trim().equals(code) || values.trim().equals("123456"))) {
                        return this.errorJSON("验证码不正确，请重新输入！");
                    }
                }


                user = appUserService.findByLoginname(loginname);

                /**
                 * 临时接口修改
                 */

                //如果用户没有注册 开始注册
                if (user == null || user.getId() == null || user.getId() <= 0) {
                    boolean flag = appUserService.registeredUser(loginname, ObjectUtil.isNull(password)?MD5Util.MD5("123456"): password, invitationcode, mobileSpec, packageName);
                    if (flag) {
                        user = appUserService.findByLoginname(loginname);
                    } else {
                        return this.errorCLJSON("注册失败");
                    }
                }
            } else {
                //账号密码登录
                if (StringEx.isNull(password)) {
                    return this.errorJSON("密码不能为空");
                }

                if (password.toLowerCase().contains("script")) {
                    return this.errorJSON("请不要做非法攻击!");
                }
                //MD5Util.MD5("123456"),

                user = appUserService.findByUser(loginname, password);
//                user = appUserService.findByUser(loginname, MD5Util.MD5(password));
                if (user == null || user.getId() == null || user.getId() <= 0) {
                    return this.errorJSON("该用户不存在或密码错误！");
                }

//                if (!user.getPassword().trim().equals(MD5Util.MD5(password))) {
//                    return this.errorJSON("用户名或密码不正确！");
//                }
            }

            if (user.getStates().intValue() == Constants.shiFou_STATE_FOU) {
                return this.errorJSON("账号已被封禁，请联系管理员!");
            }
            //如果已经登录，删除旧的用户uuid
            Object oldtObjokon = redisUtil.get(RedisKeys.userId + user.getId());
            if (oldtObjokon != null && oldtObjokon.toString().trim().length() > 0) {
                redisUtil.del(RedisKeys.userToken + oldtObjokon.toString().trim());
            }

            //用户信息加入缓存
            String token = RandomUtil.getInstance().generateString(20);
            redisUtil.set(RedisKeys.userToken + token, user.getId(), Constants.token_effective_time);
            redisUtil.set(RedisKeys.userId + user.getId(), token);
            redisUtil.set(RedisKeys.userinfo + user.getId(), user);

            //注销后12小时内重新登录，删掉注销逻辑
            String key = String.format(RedisKeys.WRITE_OFF, user.getId());
            redisUtil.del(key);

            Map<String, Object> retMap = new HashMap<>(16);
            retMap.put(ClientConstants.client_toke, token);
            UserDto ud = new UserDto();
            BeanUtils.copyProperties(user, ud);
            retMap.put("user", ud);
            AppSetup setup = appSetupService.get();
            retMap.put("gfqun", setup.getGftxcode());
            //记录登录日志
            saveUserLoginLog(user.getNick(), user.getLoginname(), user.getPic(), user.getId());

            if (ObjectUtil.isEmpty(mobileSpec)) {
                String os = UaUtil.getOs(request);
                if (ObjectUtil.isNotEmpty(os)) {
                    mobileSpec = os;
                    if(ObjectUtil.isNotEmpty(deviceModel) && deviceModel.contains("huawei")){
                        mobileSpec = deviceModel;
                    }
                }
            }
            //修改用户设备型号
            if (ObjectUtil.isNotEmpty(mobileSpec)) {
                appUserService.updateMobileSpec(user.getId(), mobileSpec);
            }

            return this.sucessJSON(retMap, "登录成功");
        } catch (Exception e) {
            logger.error("用户登录异常", e);
            return this.errorJSON("系统繁忙");
        }
    }

    @RequestMapping("/aliLogin")
    @ResponseBody
    @RedisSynchronized(key = "#accessToken", second = 5)
    public Result aliLogin(String accessToken) {
        try {
            GetMobileResponse response = GetMobileUtils.get(accessToken);
            if (response.getCode().equals("OK")) {
                String mobile = response.getGetMobileResultDTO().getMobile();
                AppUser user = appUserService.findByLoginname(mobile);
                if (user != null) {
                    if (user.getStates().intValue() == Constants.shiFou_STATE_FOU) {
                        return this.errorJSON("账号已被封禁，请联系管理员!");
                    }
                    //如果已经登录，删除旧的用户uuid
                    Object oldtObjokon = redisUtil.get(RedisKeys.userId + user.getId());
                    if (oldtObjokon != null && oldtObjokon.toString().trim().length() > 0) {
                        redisUtil.del(RedisKeys.userToken + oldtObjokon.toString().trim());
                    }
                    //用户信息加入缓存
                    String token = RandomUtil.getInstance().generateString(20);
                    redisUtil.set(RedisKeys.userToken + token, user.getId(), Constants.token_effective_time);
                    redisUtil.set(RedisKeys.userId + user.getId(), token);
                    redisUtil.set(RedisKeys.userinfo + user.getId(), user);
                    Map<String, Object> retMap = new HashMap<>(16);
                    retMap.put(ClientConstants.client_toke, token);
                    UserDto ud = new UserDto();
                    BeanUtils.copyProperties(user, ud);
                    retMap.put("user", ud);
                    AppSetup setup = appSetupService.get();
                    retMap.put("gfqun", setup.getGftxcode());
                    retMap.put("isFirstRegister", 0);
                    //记录登录日志
                    saveUserLoginLog(user.getNick(), user.getLoginname(), user.getPic(), user.getId());
                    return this.sucessJSON(retMap, "登录成功");
                } else {
                    Map<String, Integer> loginNameMap = (Map<String, Integer>) redisUtil.get(RedisKeys.yonghu_all_yaoqingma);
                    if (loginNameMap == null) {
                        loginNameMap = new HashMap<>(16);
                    }
                    String packageName = null;
                    //判断平台
                    String header = request.getHeader(ClientConstants.packageName);
                    if (ObjectUtil.isNotEmpty(header)) {
                        packageName = header;
                    } else {
                        packageName = "lyq";
                    }
                    boolean flag = appUserService.registeredUser(mobile, MD5Util.MD5("123456"), null, null, packageName);
                    if (flag) {
                        user = appUserService.findByLoginname(mobile);
                        //把手机号加入缓存
                        loginNameMap.put(user.getLoginname(), user.getId());
                        redisUtil.set(RedisKeys.yonghu_all_yaoqingma, loginNameMap);
                        String uuid = RandomUtil.getInstance().generateString(23);
                        //用户信息加入缓存
                        redisUtil.set(uuid, user.getId(), Constants.token_effective_time);

                        Map<String, Object> retMap = new HashMap<>(16);
                        retMap.put("isFirstRegister", 1);
                        return this.sucessJSON(retMap, "注册成功");
                    } else {
                        return this.errorCLJSON("注册失败");
                    }
                }
            } else {
                return this.errorCLJSON("alilogin-error");
            }
        } catch (Exception e) {
            logger.error("用户登录异常", e);
            return this.errorJSON("系统繁忙");
        }
    }

    /**
     * 三方登录
     *
     * @param appUser
     * @return
     */
    @RequestMapping("/thirdTokenLogin")
    @ResponseBody
    @RedisSynchronized(key = "#appUser.thirdToken", second = 5)
    public Result thirdTokenLogin(AppUser appUser) {
        try {
            if (StringEx.isNull(appUser.getThirdType())) {
                return this.errorJSON("登录类型错误");
            } else {
                if (!appUser.getThirdType().equals("weixin") && !appUser.getThirdType().equals("qq") && !appUser.getThirdType().equals("apple")) {
                    return this.errorJSON("登录类型错误");
                }
            }
            if (StringEx.isNull(appUser.getThirdToken())) {
                return this.errorJSON("未获取到第三方登录TOKEN授权");
            }

            AppUser userByThirdToken = appUserService.findUserByThirdToken(appUser.getThirdType(), appUser.getThirdToken());
            if (userByThirdToken != null) {
                //如果已经登录，删除旧的用户uuid
                Object oldtObjokon = redisUtil.get(RedisKeys.userId + userByThirdToken.getId());
                if (oldtObjokon != null && oldtObjokon.toString().trim().length() > 0) {
                    redisUtil.del(RedisKeys.userToken + oldtObjokon.toString().trim());
                }
                //用户信息加入缓存
                String token = RandomUtil.getInstance().generateString(20);
                redisUtil.set(RedisKeys.userToken + token, userByThirdToken.getId(), Constants.token_effective_time);
                redisUtil.set(RedisKeys.userId + userByThirdToken.getId(), token);
                redisUtil.set(RedisKeys.userinfo + userByThirdToken.getId(), userByThirdToken);

                Map<String, Object> retMap = new HashMap<>(16);
                retMap.put(ClientConstants.client_toke, token);
                UserDto ud = new UserDto();
                BeanUtils.copyProperties(userByThirdToken, ud);
                retMap.put("user", ud);
                AppSetup setup = appSetupService.get();
                retMap.put("gfqun", setup.getGftxcode());
                retMap.put("isBuilding", 1);
                //记录登录日志
                saveUserLoginLog(userByThirdToken.getNick(), userByThirdToken.getLoginname(), userByThirdToken.getPic(), userByThirdToken.getId());
                return this.sucessJSON(retMap, "登录成功");
            } else {
                Map<String, Object> retMap = new HashMap<>(16);
                retMap.put("isBuilding", 0);
                return this.sucessJSON(retMap, "登录成功");
            }
//            return this.sucessJSON("登录成功");
        } catch (Exception e) {
            logger.error("第三方登录异常" + appUser.getThirdType(), e);
            return this.errorJSON("网络繁忙");
        }
    }

    /**
     * 三方登录注册绑定手机号
     *
     * @param appUser
     * @return
     */
    @RequestMapping("/thirdTokenRegister")
    @ResponseBody
    @RedisSynchronized(key = "#appUser.loginname", second = 5)
    public Result thirdTokenRegister(AppUser appUser) {
        if (StringEx.isNull(appUser.getThirdType())) {
            return this.errorJSON("登录类型错误");
        } else {
            if (!appUser.getThirdType().equals("weixin") && !appUser.getThirdType().equals("qq") && !appUser.getThirdType().equals("apple")) {
                return this.errorJSON("登录类型错误");
            }
        }
        if (StringEx.isNull(appUser.getThirdToken())) {
            return this.errorJSON("未获取到第三方登录TOKEN授权");
        }
        if (StringEx.isNull(appUser.getLoginname())) {
            return this.sucessJSON("请绑定手机号");
        }
        if (StringEx.isNull(appUser.getMobileCode())) {
            return this.errorJSON("请输入验证码");
        }
        boolean exits = redisUtil.hasKey(RedisKeys.zcyzm + appUser.getLoginname());
        if (!exits) {
            return this.errorJSON("验证码不能为空！");
        }
        String values = redisUtil.get(RedisKeys.zcyzm + appUser.getLoginname()).toString();
        if (StringEx.isNull(values)) {
            return this.errorJSON("验证码已过期，请重新获取验证码！");
        }
        if (!values.trim().equals(appUser.getMobileCode())) {
            return this.errorJSON("验证码不正确，请重新输入！");
        }
        AppUser byLoginname = appUserService.findByLoginname(appUser.getLoginname());
        if (byLoginname != null) {
            //如果已经登录，删除旧的用户uuid
            Object oldtObjokon = redisUtil.get(RedisKeys.userId + byLoginname.getId());
            if (oldtObjokon != null && oldtObjokon.toString().trim().length() > 0) {
                redisUtil.del(RedisKeys.userToken + oldtObjokon.toString().trim());
            }
            //用户信息加入缓存
            String token = RandomUtil.getInstance().generateString(20);
            redisUtil.set(RedisKeys.userToken + token, byLoginname.getId(), Constants.token_effective_time);
            redisUtil.set(RedisKeys.userId + byLoginname.getId(), token);
            redisUtil.set(RedisKeys.userinfo + byLoginname.getId(), byLoginname);
            appUserService.updateUserThirdToken(byLoginname.getId(), appUser.getThirdType(), appUser.getThirdToken());
            AppUser byLoginname1 = appUserService.findByLoginname(appUser.getLoginname());
            Map<String, Object> retMap = new HashMap<>(16);
            retMap.put(ClientConstants.client_toke, token);
            UserDto ud = new UserDto();
            BeanUtils.copyProperties(byLoginname1, ud);
            retMap.put("user", ud);
            AppSetup setup = appSetupService.get();
            retMap.put("gfqun", setup.getGftxcode());
            retMap.put("isBuilding", 1);


            //记录登录日志
            saveUserLoginLog(byLoginname.getNick(), byLoginname.getLoginname(), byLoginname.getPic(), byLoginname.getId());
            return this.sucessJSON(retMap, "登录成功");
        } else {
            boolean b = appUserService.addUserThirdToken(appUser.getLoginname(), appUser.getThirdToken(), appUser.getThirdType());
            Map<String, Integer> loginNameMap = (Map<String, Integer>) redisUtil.get(RedisKeys.yonghu_all_yaoqingma);
            if (loginNameMap == null) {
                loginNameMap = new HashMap<>(16);
            }
            if (b) {
                AppUser user = appUserService.findByLoginname(appUser.getLoginname());
                //把手机号加入缓存
                loginNameMap.put(user.getLoginname(), user.getId());
                redisUtil.set(RedisKeys.yonghu_all_yaoqingma, loginNameMap);
                String uuid = RandomUtil.getInstance().generateString(23);
                //用户信息加入缓存
                redisUtil.set(uuid, user.getId(), Constants.token_effective_time);
                //删除验证码
                redisUtil.del(RedisKeys.zcyzm + appUser.getLoginname());

                //用户信息加入缓存
                String token = RandomUtil.getInstance().generateString(20);
                redisUtil.set(RedisKeys.userToken + token, user.getId(), Constants.token_effective_time);
                redisUtil.set(RedisKeys.userId + user.getId(), token);
                redisUtil.set(RedisKeys.userinfo + user.getId(), user);

                Map<String, Object> retMap = new HashMap<>(16);
                retMap.put(ClientConstants.client_toke, token);
                UserDto ud = new UserDto();
                BeanUtils.copyProperties(user, ud);
                retMap.put("user", ud);
                AppSetup setup = appSetupService.get();
                retMap.put("gfqun", setup.getGftxcode());
                retMap.put("isBuilding", 1);
                //记录登录日志
                saveUserLoginLog(user.getNick(), user.getLoginname(), user.getPic(), user.getId());
                return this.sucessJSON(retMap, "登录成功");
            } else {
                return this.errorJSON("登录失败");
            }
        }
    }


    /**
     * 绑定TOKEN信息获取登录Token,没有TOKEN去绑定用户
     *
     * @param code
     * @param type
     * @return
     */
    @RequestMapping("/bingToken")
    @ResponseBody
    @EnableApiLimit(count = 10, time = 1000)
    public Result bingToken(String code, Integer type) {
        try {
            if (StringUtils.isBlank(code)) return this.errorJSON("token错误");
            AppUser user;
            if (type == 1) {
                user = appUserService.findByGooleId(code);
            } else if (type == 2) {
                user = appUserService.findByFaccBackId(code);
            } else if (type == 3) {
                user = appUserService.findByAppleBackId(code);
            } else {
                return this.errorJSON("type error");
            }
            if (Objects.isNull(user)) return errorJSON("token不存在");
            if (user.getStates().intValue() == Constants.shiFou_STATE_FOU) {
                return this.errorJSON("token不存在");
            }
            //如果已经登录，删除旧的用户uuid
            Object oldtObjokon = redisUtil.get(RedisKeys.userId + user.getId());
            if (oldtObjokon != null && oldtObjokon.toString().trim().length() > 0) {
                redisUtil.del(RedisKeys.userToken + oldtObjokon.toString().trim());
            }
            //用户信息加入缓存
            String token = DigestUtils.md5Hex(RandomUtil.getInstance().generateString(60));
            redisUtil.set(RedisKeys.userToken + token, user.getId(), Constants.token_effective_time);
            redisUtil.set(RedisKeys.userId + user.getId(), token);
            redisUtil.set(RedisKeys.userinfo + user.getId(), user);
            Map<String, Object> retMap = new HashMap<>(16);
            retMap.put(ClientConstants.client_toke, token);
            UserDto ud = new UserDto();
            BeanUtils.copyProperties(user, ud);
            retMap.put("user", ud);
            AppSetup setup = appSetupService.get();
            retMap.put("gfqun", setup.getGftxcode());
            //记录登录日志
            saveUserLoginLog(user.getNick(), user.getLoginname(), user.getPic(), user.getId());
            return this.sucessJSON(retMap, "成功");
        } catch (Exception e) {
            logger.error("系统错误：", e);
            return this.errorJSON("网络繁忙，请稍后重试");
        }
    }

    /**
     * 第三方TOKEN登录注册
     *
     * @Param: [loginname 登录名, password  密码]
     * @return: com.vf.admin.common.entity.Result
     * @Author: zhouyunyi
     * @Date: 2021/07/21
     */
    /*@RequestMapping("/tokenLogin")
    @ResponseBody
    @EnableApiLimit(count = 10, time = 1000)
    public Result login(String code, String loginname, String password, String areaCode, Integer type) {
        try {
            if (StringUtils.isBlank(code)) return errorJSON("Token error");
            if (!(type.equals(1) || type.equals(2) || type.equals(3))) return errorJSON("type error");
            if (StringEx.isNull(loginname)) return this.errorJSON("Phone number cannot be empty");
            boolean exits = redisUtil.hasKey(RedisKeys.zcyzm + loginname);
            if (!exits) {
                return this.errorJSON("Please send the verification code！");
            }
            String values = redisUtil.get(RedisKeys.zcyzm + loginname).toString();
            if (StringEx.isNull(values)) {
                return this.errorJSON("The verification code has expired！");
            }
            if (!values.trim().equals(password)) {
                return this.errorJSON("Incorrect verification code！");
            }
            if (password.toLowerCase().contains("script") || loginname.toLowerCase().contains("script")) {
                return this.errorJSON("Please don't do illegal attacks!");
            }
            AppUser user;
            user = appUserService.findByLoginname(loginname);
            if (Objects.isNull(user)) {
                boolean flag = appUserService.registeredUser(loginname, DigestUtils.md5Hex("abc123456"), null, areaCode, code, type);
                if (flag) {
                    user = appUserService.findByLoginname(loginname);
                } else {
                    return this.errorCLJSON("Registration failed");
                }
            } else {
                if (type.equals(1) && (user.getQqopenid() == null || !(user.getQqopenid().equals(code)))) {
                    user.setQqopenid(code);
                    appUserService.save(user);
                } else if (type.equals(2) && (user.getFaccebookid() == null || !(user.getFaccebookid().equals(code)))) {
                    user.setFaccebookid(code);
                    appUserService.save(user);
                } else if (type.equals(3) && (user.getAddress() == null || !(user.getAddress().equals(code)))) {
                    user.setAddress(code);
                    appUserService.save(user);
                }
            }
            if (user.getStates().intValue() == Constants.shiFou_STATE_FOU) return this.errorJSON("The account has been banned, please contact the administrator!");
            //如果已经登录，删除旧的用户uuid
            Object oldtObjokon = redisUtil.get(RedisKeys.userId + user.getId());
            if (oldtObjokon != null && oldtObjokon.toString().trim().length() > 0) {
                redisUtil.del(RedisKeys.userToken + oldtObjokon.toString().trim());
            }
            //用户信息加入缓存
            String token = RandomUtil.getInstance().generateString(20);
            redisUtil.set(RedisKeys.userToken + token, user.getId(), Constants.token_effective_time);
            redisUtil.set(RedisKeys.userId + user.getId(), token);
            redisUtil.set(RedisKeys.userinfo + user.getId(), user);

            Map<String, Object> retMap = new HashMap<>(16);
            retMap.put(ClientConstants.client_toke, token);
            UserDto ud = new UserDto();
            BeanUtils.copyProperties(user, ud);
            retMap.put("user", ud);
            AppSetup setup = appSetupService.get();
            retMap.put("gfqun", setup.getGftxcode());
            //记录登录日志
            saveUserLoginLog(user.getNick(), user.getLoginname(), user.getPic(), user.getId());
            return this.sucessJSON(retMap, "Success");
        } catch (Exception e) {
            logger.error("用户登录异常", e);
            return this.errorJSON("The system is busy,please try again later");
        }
    }*/


    /**
     * 增加用户登录日志
     *
     * @Param: [nick 昵称, phone 手机号, pic 头像, userid 用户id]
     * @return: void
     * @Author: zhouyunyi
     * @Date: 2021/07/3
     * @Time: 16:56
     */
    public void saveUserLoginLog(String nick, String phone, String pic, Integer userid) {
        String deviceModel = request.getHeader("deviceModel");
        String versionName = request.getHeader("versionName");
        String packageName = request.getHeader(ClientConstants.packageName);
        if (ObjectUtil.isEmpty(packageName)) {
            packageName = "lyq";
        }
        AppUserLoginRecord appUserLoginRecord = new AppUserLoginRecord();
        appUserLoginRecord.setLogintime(new Date());
        appUserLoginRecord.setNick(nick);
        appUserLoginRecord.setPhone(phone);
        appUserLoginRecord.setPic(pic);
        appUserLoginRecord.setUserid(userid);
        appUserLoginRecord.setDeviceModel(deviceModel);
        appUserLoginRecord.setVersionName(versionName);
        appUserLoginRecord.setPackageName(packageName);
        String ipAddress = NetworkUtil.getIpAddress(request);
        if (ObjectUtil.isNotEmpty(ipAddress)) {
            appUserLoginRecord.setIp(ipAddress);
        }
        appUserLoginRecordService.save(appUserLoginRecord);

        //用户登录后给他推送爱神牵线消息
//        sendQbtAlert(userid);
    }


    /**
     * 第一次登陆/注册完善资料
     *
     * @param image     头像文件流 【必填】
     * @param nicheng   昵称 【必填】
     * @param sex       性别  1、男  2、女 【必填】
     * @param shengri   生日
     * @param yaoqingma 邀请码
     * @return com.vf.admin.common.entity.Result
     * @author anxiang
     */
    @RequestMapping("/completeMaterial")
    @ResponseBody
    public Result completeMaterial(MultipartFile[] image, String pic, String nicheng, Integer sex, String shengri, String yaoqingma,
                                   @RequestParam(value = "password", required = false) String password) {
        try {
            //获取最新数据
            String header1 = request.getHeader(ClientConstants.client_toke);
            System.out.println(header1);
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            if (isNull(nicheng)) {
                return errorCLJSON("昵称不能为空");
            }
            if (nicheng.toLowerCase().contains("script")) {
                return this.errorJSON("请不要非法攻击");
            }
            if (StringEx.isNotNull(nicheng)) {
                if (nicheng.length() > 8) {
                    return this.errorJSON("昵称最多8字");
                }
                if (ExpressionFilter.expressionJudgment(nicheng)) {
                    return this.errorJSON("昵称不能包含特殊字符");
                }
            }
            if (isNull(sex)) {
                return errorCLJSON("请选择性别");
            }
            if (sex.intValue() != SEX_STATE_NAN && sex.intValue() != SEX_STATE_NV) {
                return this.errorJSON("请选择性别");
            }

            //防止性别被修改
            AppUser appUser = appUserService.get(userId);
            if(ObjectUtil.isNotEmpty(appUser) && ObjectUtil.isNotNull(appUser.getSex()) && ObjectUtil.notEqual(3, appUser.getSex())){
                sex = appUser.getSex();
            }

            DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
            Date sheng = new Date();
            if (isNull(shengri)) {
                sheng = format1.parse("1990-01-01");
            } else {
                sheng = format1.parse(shengri);
            }
            if (ObjectUtil.isEmpty(pic) && (image != null && image.length > 0)) {
                //上传：循环获取file数组中得文件
                MultipartFile files = image[0];
                if (!files.isEmpty()) {
                    //判断图片大小
                    if (files.getSize() <= 52428800) {
                        //上传阿里云oss
                        String ossUrl = appUserService.aliyunOssupload(files);
                        if (isNull(ossUrl)) {
                            return errorJSON("图片上传失败");
                        }
                        pic = ossUrl;
                        boolean b = OssCheckUtils.imageSyncCheckV2(ossUrl);
                        if (!b) {
                            return this.errorJSON("上传的头像违规");
                        }
                    } else {
                        return this.errorJSON("图片大小超过限制！");
                    }
                }

            } else if (ObjectUtil.isEmpty(pic)) {
                //默认头像
                //男
                if (sex.equals(1)) {
                    pic = "http://osszhiyuhn1.ptszyxx.com/default/nang.png";
                }
                //女
                if (sex.equals(2)) {
                    pic = "http://osszhiyuhn1.ptszyxx.com/default/nv.png";
                }
            }

            if (ObjectUtil.isNotEmpty(pic)) {
                boolean b = OssCheckUtils.imageSyncCheckV2(pic);
                if (!b) {
                    //男
                    if (sex.equals(1)) {
                        pic = "http://osszhiyuhn1.ptszyxx.com/default/nang.png";
                    }
                    //女
                    if (sex.equals(2)) {
                        pic = "http://osszhiyuhn1.ptszyxx.com/default/nv.png";
                    }
                }

            }
            String packageName = null;
            //判断平台
            String header = request.getHeader(ClientConstants.packageName);
            if (ObjectUtil.isNotEmpty(header)) {
                packageName = header;
            } else {
                packageName = "lyq";
            }
            boolean flag = appUserService.completeMaterial(userId, pic, nicheng, sex, sheng, yaoqingma, password,packageName);
            if (flag) {
                //用户首次注册后 推送爱神牵线消息
//                sendQbtAlert(userId);
                return this.sucessJSON("成功");
            } else {
                return this.errorCLJSON("失败");
            }
        } catch (Exception e) {
            logger.error("完善资料异常", e);
            return this.errorJSON("网络繁忙，请稍后重试");
        }
    }
//    @RequestMapping("/completeMaterial")
//    @ResponseBody
//    public Result completeMaterial(MultipartFile[] image, String nicheng, Integer sex, String shengri, String yaoqingma,
//                                   @RequestParam(value = "password", required = false) String password) {
//        try {
//            //获取最新数据
//            String token = request.getHeader(ClientConstants.client_toke);
//            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
//            if (isNull(nicheng)) {
//                return errorCLJSON("昵称不能为空");
//            }
//            if (nicheng.toLowerCase().contains("script")) {
//                return this.errorJSON("请不要非法攻击");
//            }
//            if (StringEx.isNotNull(nicheng)) {
//                if (nicheng.length() > 8) {
//                    return this.errorJSON("昵称最多8字");
//                }
//                if (ExpressionFilter.expressionJudgment(nicheng)) {
//                    return this.errorJSON("昵称不能包含特殊字符");
//                }
//            }
//            if (isNull(sex)) {
//                return errorCLJSON("请选择性别");
//            }
//            if (sex.intValue() != SEX_STATE_NAN && sex.intValue() != SEX_STATE_NV) {
//                return this.errorJSON("请选择性别");
//            }
//            DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
//            Date sheng = new Date();
//            if (isNull(shengri)) {
//                sheng = format1.parse("1990-01-01");
//            } else {
//                sheng = format1.parse(shengri);
//            }
////            String pic = "https://yunliaos.oss-cn-beijing.aliyuncs.com/image/default_head.png";
//            String pic = null;
//
//            //默认头像
//            //男
//            if (sex.equals(1)) {
//                pic = "http://osszhiyuhn1.ptszyxx.com/default/nang.png";
//            }
//            //女
//            if (sex.equals(2)) {
//                pic = "http://osszhiyuhn1.ptszyxx.com/default/nv.png";
//            }
//            //上传：循环获取file数组中得文件
//            if (image != null && image.length > 0) {
//                MultipartFile files = image[0];
//                if (!files.isEmpty()) {
//                    //判断图片大小
//                    if (files.getSize() <= 52428800) {
//                        //上传阿里云oss
//                        String ossUrl = appUserService.aliyunOssupload(files);
//                        if (isNull(ossUrl)) {
//                            return errorJSON("图片上传失败");
//                        }
//                        pic = ossUrl;
//                        boolean b = OssCheckUtils.imageSyncCheckV2(ossUrl);
//                        if (!b) {
//                            return this.errorJSON("上传的头像违规");
//                        }
//                    } else {
//                        return this.errorJSON("图片大小超过限制！");
//                    }
//                }
//            }
//            boolean flag = appUserService.completeMaterial(userId, pic, nicheng, sex, sheng, yaoqingma, password);
//            if (flag) {
//                //用户首次注册后 推送爱神牵线消息
//                sendQbtAlert(userId);
//                return this.sucessJSON("成功");
//            } else {
//                return this.errorCLJSON("失败");
//            }
//        } catch (Exception e) {
//            logger.error("完善资料异常", e);
//            return this.errorJSON("网络繁忙，请稍后重试");
//        }
//    }


    /**
     * 给用户单独发送爱神牵线消息
     *
     * @param userId
     */
    public void sendQbtAlert(Integer userId) {
        AppUser user = appUserService.get(userId);

        if (user.getSex() != null) {
            /**
             * 如果是男性用户从未联系过的女用户中选一个
             * 如果是女性用户从未联系过的男用户中选一个
             * 移除已经发过消息的用户
             * 移除牵线过的用户
             */
            if (user.getSex() == 1) {
                //获取数据女号
                List<AppUser> userListWoman = appUserService.findUserListByShuJuAndSex(2);

                List<Integer> userIdListWoman = userListWoman.stream().map(e -> e.getId()).collect(Collectors.toList());

//                List<MessageChatFrom> chatUserList = messageChatFromService.getByUserId(userId);
//
//
//                List<Integer> toUserIdCollect = chatUserList.stream().filter(e -> e.getFromUserId() == userId).map(e -> e.getToUserId()).collect(Collectors.toList());
//
//                List<Integer> fromUserIdCollect = chatUserList.stream().filter(e -> e.getToUserId() == userId).map(e -> e.getFromUserId()).collect(Collectors.toList());
//
//
//                userIdListWoman.removeAll(toUserIdCollect);
//                userIdListWoman.removeAll(fromUserIdCollect);
//
//                List<LovelyGodLog> lovelyGodLogs = lovelyGodLogService.listByManId(userId);
//                List<Integer> collect = lovelyGodLogs.stream().map(e -> e.getWomanUserId()).collect(Collectors.toList());
//                userIdListWoman.removeAll(collect);

                Collections.shuffle(userIdListWoman);
                if (userIdListWoman != null && userIdListWoman.size() > 0) {
                    List<Integer> qbtWoManList = userIdListWoman.subList(0, 3);
                    System.out.println("用户id" + qbtWoManList);

                    qbtWoManList.forEach(e -> {

                        AppUser matchUser = appUserService.get(e);
                        TxIm.sendUserMsgqbt(matchUser.getTengxuncode(), user.getTengxuncode(), "←爱神牵线→，你和他很有缘哦，为你们牵线成功~");
                        TxIm.sendUserMsgqbt(user.getTengxuncode(), matchUser.getTengxuncode(), "←爱神牵线→，你和他很有缘哦，为你们牵线成功，给她发个消息吧~");

                        TxIm.sendUserMsgqbtAlert(matchUser.getTengxuncode(), user.getTengxuncode(), "♥爱神牵线成功♥，给对方发送消息可领取系统红包和礼物哦，快来回复吧！");
                        TxIm.sendUserMsgqbtAlert(user.getTengxuncode(), matchUser.getTengxuncode(), "爱神牵线聊天由男生支付钻石，对方设置了消息收费" + matchUser.getMessagePrice() + "钻石/条");
                        lovelyGodLogService.add(user.getId(), matchUser.getId());

                        String key = String.format(RedisKeys.LOVELY_GOD, user.getId(), matchUser.getId());
                        redisUtil.set(key, "1", Constants.RedisKeysLife.hours_12);
                    });


                }
            } else if (user.getSex() == 2) {
                List<AppUser> userListMan = appUserService.findUserListBySex(1);
                List<Integer> userIdListMan = userListMan.stream().map(e -> e.getId()).collect(Collectors.toList());
//                List<MessageChatFrom> chatUserList = messageChatFromService.getByUserId(userId);
//
//                List<Integer> toUserIdCollect = chatUserList.stream().filter(e -> e.getFromUserId() == userId).map(e -> e.getToUserId()).collect(Collectors.toList());
//                List<Integer> fromUserIdCollect = chatUserList.stream().filter(e -> e.getToUserId() == userId).map(e -> e.getFromUserId()).collect(Collectors.toList());
//                userIdListMan.removeAll(toUserIdCollect);
//                userIdListMan.removeAll(fromUserIdCollect);
//
//                List<LovelyGodLog> lovelyGodLogs = lovelyGodLogService.listByWoManId(userId);
//                List<Integer> collect = lovelyGodLogs.stream().map(e -> e.getManUserId()).collect(Collectors.toList());
//                userIdListMan.removeAll(collect);

                Collections.shuffle(userIdListMan);
                if (userIdListMan != null && userIdListMan.size() > 0) {
                    List<Integer> qbtManList = userIdListMan.subList(0, 3);

                    qbtManList.forEach(e -> {


                        AppUser matchUser = appUserService.get(e);
                        TxIm.sendUserMsgqbt(user.getTengxuncode(), matchUser.getTengxuncode(), "←爱神牵线→，你和他很有缘哦，为你们牵线成功~");
                        TxIm.sendUserMsgqbt(matchUser.getTengxuncode(), user.getTengxuncode(), "←爱神牵线→，你和他很有缘哦，为你们牵线成功，给她发个消息吧~");

                        new Thread(new Runnable() {
                            @SneakyThrows
                            @Override
                            public void run() {
                                Thread.sleep(3000);
                                TxIm.sendUserMsgqbtAlert(user.getTengxuncode(), matchUser.getTengxuncode(), "♥爱神牵线成功♥，给对方发送消息可领取系统红包和礼物哦，快来回复吧！");
                                TxIm.sendUserMsgqbtAlert(matchUser.getTengxuncode(), user.getTengxuncode(), "爱神牵线聊天由男生支付钻石，对方设置了消息收费" + matchUser.getMessagePrice() + "钻石/条");
                            }
                        }).start();
                        lovelyGodLogService.add(matchUser.getId(), user.getId());
                        String key = String.format(RedisKeys.LOVELY_GOD, matchUser.getId(), user.getId());
                        redisUtil.set(key, "1", Constants.RedisKeysLife.hours_12);
                    });

                }
            }
        }
    }


    /**
     * 给用户单独发送爱神牵线消息
     *
     * @param userId
     */
//    public void sendQbtAlert(Integer userId) {
//        AppUser user = appUserService.get(userId);
//
//        if (user.getSex() != null) {
//            /**
//             * 如果是男性用户从未联系过的女用户中选一个
//             * 如果是女性用户从未联系过的男用户中选一个
//             * 移除已经发过消息的用户
//             * 移除牵线过的用户
//             */
//            if (user.getSex() == 1) {
//                List<AppUser> userListWoman = appUserService.findUserListBySex(2);
//                List<Integer> userIdListWoman = userListWoman.stream().map(e -> e.getId()).collect(Collectors.toList());
//                List<MessageChatFrom> chatUserList = messageChatFromService.getByUserId(userId);
//
//                List<Integer> toUserIdCollect = chatUserList.stream().filter(e -> e.getFromUserId() == userId).map(e -> e.getToUserId()).collect(Collectors.toList());
//                List<Integer> fromUserIdCollect = chatUserList.stream().filter(e -> e.getToUserId() == userId).map(e -> e.getFromUserId()).collect(Collectors.toList());
//                userIdListWoman.removeAll(toUserIdCollect);
//                userIdListWoman.removeAll(fromUserIdCollect);
//
//                List<LovelyGodLog> lovelyGodLogs = lovelyGodLogService.listByManId(userId);
//                List<Integer> collect = lovelyGodLogs.stream().map(e -> e.getWomanUserId()).collect(Collectors.toList());
//                userIdListWoman.removeAll(collect);
//
//                Collections.shuffle(userIdListWoman);
//                if (userIdListWoman != null && userIdListWoman.size() > 0) {
//                    List<Integer> qbtWoManList = userIdListWoman.subList(0, 1);
//
//                    AppUser matchUser = appUserService.get(qbtWoManList.get(0));
//                    TxIm.sendUserMsgqbt(matchUser.getTengxuncode(), user.getTengxuncode(), "←爱神牵线→，你和他很有缘哦，为你们牵线成功~");
//                    TxIm.sendUserMsgqbt(user.getTengxuncode(), matchUser.getTengxuncode(), "←爱神牵线→，你和他很有缘哦，为你们牵线成功，给她发个消息吧~");
//
//                    TxIm.sendUserMsgqbtAlert(matchUser.getTengxuncode(), user.getTengxuncode(), "♥爱神牵线成功♥，给对方发送消息可领取系统红包和礼物哦，快来回复吧！");
//                    TxIm.sendUserMsgqbtAlert(user.getTengxuncode(), matchUser.getTengxuncode(), "爱神牵线聊天由男生支付钻石，对方设置了消息收费" + matchUser.getMessagePrice() + "钻石/条");
//                    lovelyGodLogService.add(user.getId(), matchUser.getId());
//
//                    String key = String.format(RedisKeys.LOVELY_GOD, user.getId(), matchUser.getId());
//                    redisUtil.set(key, "1", Constants.RedisKeysLife.hours_12);
//                }
//            } else if (user.getSex() == 2) {
//                List<AppUser> userListMan = appUserService.findUserListBySex(1);
//                List<Integer> userIdListMan = userListMan.stream().map(e -> e.getId()).collect(Collectors.toList());
//                List<MessageChatFrom> chatUserList = messageChatFromService.getByUserId(userId);
//
//                List<Integer> toUserIdCollect = chatUserList.stream().filter(e -> e.getFromUserId() == userId).map(e -> e.getToUserId()).collect(Collectors.toList());
//                List<Integer> fromUserIdCollect = chatUserList.stream().filter(e -> e.getToUserId() == userId).map(e -> e.getFromUserId()).collect(Collectors.toList());
//                userIdListMan.removeAll(toUserIdCollect);
//                userIdListMan.removeAll(fromUserIdCollect);
//
//                List<LovelyGodLog> lovelyGodLogs = lovelyGodLogService.listByWoManId(userId);
//                List<Integer> collect = lovelyGodLogs.stream().map(e -> e.getManUserId()).collect(Collectors.toList());
//                userIdListMan.removeAll(collect);
//
//                Collections.shuffle(userIdListMan);
//                if (userIdListMan != null && userIdListMan.size() > 0) {
//                    List<Integer> qbtManList = userIdListMan.subList(0, 1);
//
//                    AppUser matchUser = appUserService.get(qbtManList.get(0));
//                    TxIm.sendUserMsgqbt(user.getTengxuncode(), matchUser.getTengxuncode(), "←爱神牵线→，你和他很有缘哦，为你们牵线成功~");
//                    TxIm.sendUserMsgqbt(matchUser.getTengxuncode(), user.getTengxuncode(), "←爱神牵线→，你和他很有缘哦，为你们牵线成功，给她发个消息吧~");
//
//                    new Thread(new Runnable() {
//                        @SneakyThrows
//                        @Override
//                        public void run() {
//                            Thread.sleep(3000);
//                            TxIm.sendUserMsgqbtAlert(user.getTengxuncode(), matchUser.getTengxuncode(), "♥爱神牵线成功♥，给对方发送消息可领取系统红包和礼物哦，快来回复吧！");
//                            TxIm.sendUserMsgqbtAlert(matchUser.getTengxuncode(), user.getTengxuncode(), "爱神牵线聊天由男生支付钻石，对方设置了消息收费" + matchUser.getMessagePrice() + "钻石/条");
//                        }
//                    }).start();
//                    lovelyGodLogService.add(matchUser.getId(), user.getId());
//                    String key = String.format(RedisKeys.LOVELY_GOD, matchUser.getId(), user.getId());
//                    redisUtil.set(key, "1", Constants.RedisKeysLife.hours_12);
//                }
//            }
//        }
//    }


//    /**
//     * 一键搭讪
//     * 传入用户id逗号隔开
//     */
//    @ResponseBody
//    @RequestMapping("/onceClickChat")
//    public Result onceClickChat(String userIds){
//
//
//        return null;
//    }

}
